package com.xhui.vimarket.zkplus.utils.zul;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Tree;
import org.zkoss.zul.Treeitem;

import com.xhui.vimarket.zkplus.zul.tree.node.TreeNode;
import com.xhui.vimarket.zkplus.zul.tree.node.TreeNodeEntity;
import com.xhui.vimarket.zkplus.zul.tree.render.BaseTreeitemRenderer;
import com.xhui.vimarket.zkplus.zul.tree.render.ListTreeitemRender;

/**
 * ComboboxUtil.
 * 
 * @author wuyx
 * @version Revision 1.0.0
 * 
 */
public final class TreeUtil {
    
    /**
     * 私有构造函数.
     */
    private TreeUtil() {
    }
    
    /**
     * 根据传入节点，删除树展示节点.
     * @param treeitem Treeitem
     */
    public static void removeNode(final Treeitem treeitem) {
        if (treeitem != null) {
            final Component itemparent = treeitem.getParent();
            if (itemparent != null) {
                itemparent.removeChild(treeitem);
            }
        }
    }
    
    /**
     * 根据传入节点值，更新树展示节点,不含子节点.
     * @param treeitem Treeitem
     * @param val Object
     */
    public static void refreshNode(final Treeitem treeitem, final Object val) {
        TreeUtil.refreshNode(treeitem, val, false);
    }
    
    /**
     * 根据传入节点值，更新树展示节点.
     * @param treeitem Treeitem
     * @param nodeval Object Node
     * @param refreshChilds 是否刷新子节点
     */
    private static void refreshNode(final Treeitem treeitem, final Object nodeval,
        final boolean refreshChilds) {
        if (treeitem != null && nodeval != null) {
            treeitem.getTreerow();
            if (nodeval instanceof TreeNodeEntity) {
                ListTreeitemRender.updateRender(treeitem, nodeval);
            } else if (nodeval instanceof TreeNode) {
                BaseTreeitemRenderer.updateRender(treeitem, nodeval);
            }
        }
    }
    
    /**
     * 选中首个节点.
     * @param tree Tree
     * @author wuyx
     * 2011-1-29 wuyx 
     */
    public static void selectFirstItem(final Tree tree) {
        if (tree != null && tree.getTreechildren() != null
            && tree.getTreechildren().getItemCount() > 0
            && tree.getTreechildren().getFirstChild() instanceof Treeitem) {
            tree.setSelectedItem((Treeitem) tree.getTreechildren().getFirstChild());
            Events.sendEvent(Events.ON_SELECT, (Treeitem) tree.getTreechildren().getFirstChild(),
                null);
        }
    }
}
